<template>
  <div>
    <Header :left="false" title="设备点检" />
    <Row style="margin-top: 80px;">
      <div class="container dwo">
        <div class="card_under" v-if="taskItemList !== undefined">
          <div v-for="(item, index) in taskItemList" :key="index">
            <div v-if="item.actived">
              <Col span="16" class="container dwo">
              <span class="text">
                {{ item.itemName }}
                <span v-if="item.equipType == '1'">(辅助设备)</span>
              </span>
              </Col>
              <Col span="8">
              <VanImage width="6rem" height="2.2rem" style="margin-top:2px;" fit="fill"
                :src="taskFileList != [] ? taskFileList[0] : ''" @click="imageShow" />
              </Col>
              <Divider
                :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px', margin: '10px 0!important' }" />
              <span class="text_scan">
                共
                <Tag plain type="primary" size="large">{{ taskItemList.length }}</Tag>&nbsp;项，已检
                <Tag type="primary" size="large">{{ index }}</Tag>&nbsp;项，待检
                <Tag type="danger" size="large">{{ taskItemList.length - index }}</Tag>&nbsp;项
              </span>

              <Divider
                :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px', margin: '12px 0 0 0!important' }">
                {{ index + 1 }}、{{ item.itemDesc }}</Divider>
              <Field name="checkres" label="检查结果">
                <template #input>
                  <RadioGroup v-model="item.itemResult" @change="radioChange" direction="horizontal">
                    <Radio name="1">合格</Radio>
                    <Radio name="0">不合格</Radio>
                  </RadioGroup>
                </template>
              </Field>
              <Field name="checkres" label="标准图片">
                <template #input>
                  <VanImage width="12rem" height="7rem" fit="fill" :src="item.filePath" />
                </template>
              </Field>
              <Field v-if="item.executeMeans == 1" name="checkres" @click="showCamera" label="点击拍照上传" />
              <div v-if="item.executeMeans == 1 && item.resourceList !== undefined && item.resourceList.length > 0">
                <div class="van-uploader" v-for="(imgUrl, ks) in item.resourceList" :key="ks">
                  <div class="van-uploader__wrapper">
                    <div class="van-uploader__preview">
                      <div @click="picShow(ks)" class="van-image van-uploader__preview-image">
                        <img :src="imgUrl" class="van-image__img" />
                      </div>
                      <div class="van-uploader__preview-delete" @click="remove(imgUrl)">
                        <i class="van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <Field v-if="item.executeMeans == 2" name="checkres" label="视频拍摄">
                <template #input>
                  <Button class="mg5" icon="play-circle" plain round hairline size="small" type="primary"
                    @click="startVideoRecord">录制</Button>
                  <Button class="mg5" v-if="item.resourceList != [] && item.resourceList.length > 0" plain round
                    icon="browsing-history" hairline size="small" type="info"
                    @click="showVideoPlay(item.resourceList[0])">预览</Button>
                  <Button class="mg5" plain round hairline icon="close" size="small" type="warning"
                    @click="clearVideoCache(item.resourceList[0])">清除</Button>
                </template>
              </Field>
              <Field v-if="item.itemResult == 0" v-model="item.remark" rows="1" autosize label="不合格原因" type="textarea"
                placeholder="请输入不合格原因" />
              <Row gutter="10">
                <Col span="12">
                <Button plain type="warning" class="btn_margin" @click="resolve">故障处理</Button>
                <Button v-if="(taskItemList.length - 1) > index" class="btn_margin" @click="jump">跳过</Button>
                </Col>
                <Col span="12">
                <Button plain type="info" class="btn_margin" v-if="index > 0" @click="back">上一步</Button>
                <Button type="info" plain class="btn_margin" v-if="(taskItemList.length - 1) > index"
                  @click="next">下一步</Button>
                <Button type="info" :loading="btnLoading" loading-text="保存中" class="btn_margin"
                  v-if="(taskItemList.length - 1) == index" @click="doCheck">保存</Button>
                </Col>
              </Row>
            </div>
          </div>
        </div>
      </div>
    </Row>
  </div>
</template>
<script>
import { Icon, Button, Image as VanImage, Col, Row, Tag, Toast, Divider, ImagePreview, Field, CellGroup, Cell, RadioGroup, Radio, Uploader, Overlay } from "vant";
import Header from "@/components/header.vue";
import { storage, memory } from '@/libs/utils';
import { _httpClient } from '@/libs/api';

Vue.use(ImagePreview);
export default {
  name: "equip_check",
  components: { Button, Header, VanImage, Col, Icon, Row, Tag, ImagePreview, Toast, Divider, Field, CellGroup, Cell, Uploader, RadioGroup, Radio, Overlay },
  data() {
    return {
      show: true,
      btnLoading: false,
      equip: {
        equipCode: '',
        equipName: '',
      },
      index: 0,
      user: {
        classes: '',
        nickName: '',
        depart: ''
      },
      taskItemList: [],
      taskFileList: []
    };
  },
  created() {
    this.user = JSON.parse(storage.get('user'));
    this.equip.equipCode = api.pageParam.equipCode;
    this.taskItemList = api.pageParam.taskItemList;
    this.taskFileList = api.pageParam.taskFileList;
    if (this.taskItemList != [] && this.taskItemList.length > 0) {
      this.taskItemList[0].actived = true;
    }
    api.requestPermission({
      list: ['camera', 'microphone', 'storage']
    }, function (ret, err) {
    });

    try {
      var manageStorage = api.require("manageStorage");
      manageStorage.getDeviceVersion({}, function (rett) {
        if (Number(rett.version) >= 30) {
          manageStorage.hasAllFilePermission({}, function (ret) {
            if (ret.status == true) {
              return;
            } else {
              manageStorage.requestAllFilePermission({}, function (ret) {});
            }
          });
        } else {
          return;
        }
      });
    } catch {}

    this.imageShow();
  },
  mounted() {
    //退出提示
    var ci = 0;
    var time1, time2;
    let that = this;
    that.$ac.addEventListener(
      {
        name: "keyback"
      },
      function (ret, err) {
        if (ci == 0) {
          time1 = new Date().getTime();
          ci = 1;
          api.toast({
            msg: "再按一次返回键离开当前页面"
          });
        } else if (ci == 1) {
          time2 = new Date().getTime();
          if (time2 - time1 < 3000) {
            that.$ac.confirm({
              title: '点检数据未保存',
              msg: '表单数据未保存，直接离开会丢失，请确认是否保存？',
              buttons: ['确定', '坚决离开', '我再想想']
            }, function (ret, err) {
              if (ret.buttonIndex == 1) {
                //保存数据
                that.saveTaskitem();
              } else if (ret.buttonIndex == 2) {
                that.$ac.closeWin();
              } else {
                // if you have a dream, why not give up?
              }
            });
          } else {
            ci = 0;
            api.toast({
              msg: "再按一次返回键离开当前页面"
            });
          }
        }
      }
    );
  },
  methods: {
    resolve() {
      let that = this;
      that.$ac.confirm({
        title: '故障处理',
        msg: '请选择故障处理类型',
        buttons: ['取消', '自修', '报修']
      }, function (ret, err) {
        if (ret.buttonIndex == 1) {
          // if you have a dream, why not give up?
        } else if (ret.buttonIndex == 2) {
          that.$ac.openWin({
            name: 'equip_self_report',
            url: "./demos-equip_self_report.html",
            pageParam: {
              equipCode: that.equip.equipCode,
              equipName: that.taskItemList[that.index].equipName,
              eqKey: that.taskItemList[that.index].eqKey,
            }
          });
        } else {
          that.$ac.openWin({
            name: 'equip_fix_report',
            url: "./demos-equip_fix_report.html",
            pageParam: {
              equipCode: that.equip.equipCode,
              equipName: that.taskItemList[that.index].equipName,
              eqKey: that.taskItemList[that.index].eqKey
            }
          });
        }
      });

    },
    radioChange(str) {
      //清空remark
      if (str == '1') {
        this.taskItemList[this.index].remark = '';
      }
    },
    remove(picUrl) {
      if (picUrl != undefined && picUrl != '' && picUrl != null) {
        let fname = picUrl.substring(picUrl.lastIndexOf("/") + 1);
        this.delObj(picUrl, fname);
      }
    },
    //调用
    async putObj(fType, fUrl) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等..."
      });
      try {
        let res = await _httpClient.postFile(_httpClient.getApiPrefix() + '/minio/oss/putObject', {
          files: {
            file: fUrl
          }
        });
        if (res.code === 200) {
          if (res.fileUrl) {
            Toast.clear();
            this.taskItemList[this.index].resourceList.push(res.fileUrl);
          }
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    showCamera() {
      let _this = this;
      api.getPicture({
        sourceType: 'camera',
        encodingType: 'jpg',
        mediaValue: 'pic',
        allowEdit: false,
        destinationType: 'url',
        quality: 60
      }, function (ret, err) {
        // 获取拍照数据并处理
        if (ret) {
          let imgSrc = ret.data;
          if (imgSrc && imgSrc != '') {
            _this.putObj('pic', imgSrc);
          }
        }
      });
    },
    saveTaskitem() {
      //alert(JSON.stringify(this.taskItemList));
    },
    jump() {
      this.taskItemList[this.index].itemResult = 2;
      this.taskItemList[this.index].remark = '';
      this.next();
    },
    back() {
      this.index -= 1;
      if (this.taskItemList.length > this.index) {
        for (let i = 0; i < this.taskItemList.length; i++) {
          if (this.index != i) {
            this.taskItemList[i].actived = false;
          }
          this.taskItemList[this.index].actived = true;
        }
      }
    },
    next() {
      this.index += 1;
      if (this.taskItemList.length > this.index) {
        for (let i = 0; i < this.taskItemList.length; i++) {
          if (this.index != i) {
            this.taskItemList[i].actived = false;
          }
        }
        this.taskItemList[this.index].actived = true;
      }
    },
    imageShow() {
      ImagePreview({
        images: this.taskFileList || [],
        showIndicators: true,
        showIndex: false
      });
    },
    picShow(picIndex) {
      ImagePreview({
        images: this.taskItemList[this.index].resourceList || [],
        showIndicators: true,
        startPosition: picIndex || 0,
        showIndex: false
      });
    },
    async doCheck() {
      let that = this;
      that.btnLoading = true;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "正在保存..."
      });
      let res = await _httpClient.post(_httpClient.getApiPrefix() + '/equip/check/saveOrUpdate', { body: this.taskItemList });
      Toast.clear();
      if (res.code === 200) {
        that.btnLoading = false;
        Toast(res.msg);
        that.$ac.closeWin();
      }
    },
    async delObj(picUrl, fname) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等..."
      });
      try {
        let res = await _httpClient.delete(_httpClient.getApiPrefix() + '/minio/oss/' + fname);
        if (res.code === 200) {
          Toast.clear();
          let flist = this.taskItemList[this.index].resourceList;
          for (var i = 0; i < flist.length; i++) {
            if (flist[i] == picUrl) {
              flist.splice(i, 1);
            }
          }
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    startVideoRecord() {
      let that = this;
      let zySmallVideo = that.$ac.require("zySmallVideo");
      zySmallVideo.openNew({
        rect: {//模块 附于一个frame之上
          x: 0,
          y: 0,
          w: api.frameWidth,
          h: api.frameHeight,
        },
        fixedOn: api.frameName,
        fixed: true,
        videoInfo: {//视频高级设置 不懂请勿修改
          //videoSize_w:720,//视频分辨率 宽 默认720 
          //videoSize_h:1280,//视频分辨率 高 默认1280
          setOutputFormat: 2,//录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
          setVideoEncoder: 2,//编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
          setAudioEncoder: 3,//音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
        },
        MaxRecordTime: 60,//最大录制时间 单位秒 默认10
        MinRecordTime: 5,//最短录制时间  单位s
        MinTimeText: "还没到时间呢",//最短时间提示词
        setFeatures: 1002,//设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
        setTip: "长按拍摄",//设置按钮上的提示词   长按拍摄等 默认空
        setBackIcon: "",//自定义返回图标 默认向下键头  支持widget  fs 等路径图片
        setBackShow: 1,//设置返回图标是否显示 1是 0否  默认1
        setCameraIcon: "",//自定义切换摄像头图标  支持widget  fs 等路径图片
        setCameraShow: 1,//右上角切换摄像头是否显示 1是 0否 默认1
        cameraInfo: {//摄像头 设置样式
          fit_xy: false,//图片是否拉伸占满宽高  默认false
          //w:120,// 摄像头宽度 默认 120
          //h:92,// 摄像头高度 默认 92
          margin_l: 0,//距左 默认都是0
          margin_r: 35,//距右
          margin_t: 65,//距上
          margin_b: 0,//距下
        },
        foucsInfo: {//点击的对焦框 样式
          color: "#cd0000",//线条颜色 默认16AE16
          width: 4,//线条宽度 默认4
        },
        recordInfo: {//录制时的参数
          //button_radius:120,//外圆半径 默认120
          //button_inside_radius:90,//内圆半径 默认90
          progress_color: "#cd0000",//进度条颜色 默认16AE16
          outside_color: "#DCDCDC",//外圆背景色 默认DCDCDC
          inside_color: "#FFFFFF",//内圆背景色 默认FFFFFF
          //strokeWidth:15,//进度条宽度 默认15
          //outside_add_size:48,//长按外圆半径变大的Size 默认48
          //inside_reduce_size:30,//长按内圆缩小的Size 默认30
        },
        confirmInfo: {//确认框参数
          fit_xy: false,//图片是否拉伸占满宽高  默认false
          img: "",//设置自定义图片
          //w:220,//宽 默认200
          //h:220,//高 默认200
          //margin_r:170, //确认按距右
        },
        cancelInfo: {//取消框参数
          fit_xy: false,//图片是否拉伸占满宽高  默认false
          img: "",//设置自定义图片
          //w:220,//宽 默认200
          //h:220,//高 默认200
          //margin_l:170,//确认按距左
        },
      }, function (ret, err) {
        if (ret.status) {
          if (ret.type == "recordSuccess") {
            that.putObj('video', ret.url);
          }
        }
      });
    },
    showVideoPlay(videoUrl) {
      let that = this;
      if (!videoUrl) {
        Toast('请先录制视频');
        return;
      }
      that.$ac.openVideo({
        url: videoUrl
      });
    },
    showVideoPlay1(videoUrl) {
      //alert(videoUrl);
      return;
      let that = this;
      let zySmallVideo = that.$ac.require("zySmallVideo");
      if (!that.fileUrl) {
        Toast('请先录制视频');
        return;
      }
      zySmallVideo.getThumbnail({
        fileUrl: that.fileUrl,
      }, function (ret, err) {
        //alert(JSON.stringify(ret));
        // document.getElementById('videoPic').src = ret.filePic;
      });
    },
    clearVideoCache(videoUrl) {
      let zySmallVideo = this.$ac.require("zySmallVideo");
      if (videoUrl != undefined && videoUrl != '' && videoUrl != null) {
        let videoName = videoUrl.substring(videoUrl.lastIndexOf("/") + 1);
        this.delObj(videoUrl, videoName);
      }
      zySmallVideo.clearCache({
      }, function (ret, err) {
        Toast.success({
          message: '清理成功'
        });
      });
    }
  }
};
</script>
<style scoped>
html,
body {
  font-family: 'Open Sans', sans-serif;
}

.mg5 {
  margin-right: 5px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: center;
}

.card_under {
  height: 620px;
  width: 95%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #4e4a67;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.btn_margin {
  margin: 2px 0 0 2%;
}

.text_scan {
  font-size: 16px;
  color: #4e4a67;
  margin: auto auto auto 20px;
  line-height: 1.5em;
  text-align: justify;
}

.img_test {
  margin-top: 20px;
  font-size: 0;
  padding-left: 20px;
}

.content-img {
  height: 60px;
  width: 60px;
  margin-bottom: 20px;
  margin-right: 20px;
  display: inline-block;
}

.content-img>img {
  height: 60px;
  width: 60px;
}

.content-img .image-remove {
  background-color: white;
  color: #ececec;
  font-size: 10px;
  width: 10px;
  height: 10px;
  text-align: center;

  border-radius: 100%;
  transform: rotate(45deg);
  cursor: pointer;
  opacity: 0.5;
  top: 1px;
  right: 1px;
  display: block;
  position: absolute;
}
</style>


